package com.java2020.online_mall.controller;

import com.google.gson.Gson;
import com.java2020.online_mall.model.Result;
import com.java2020.online_mall.model.User;
import com.java2020.online_mall.service.UserService;
import com.java2020.online_mall.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @PackgeName: ${PACKAGE_NAME}
 * @Author: MNHK
 * Date: 2020/5/2 21:39
 * @Version:1.8
 */

@WebServlet("/api/admin/user/*")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();
    Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String correct = requestURI.replace("/api/admin/user/", "");

        if("allUser".equals(correct)){
            allUser(request, response);
        }else if("deleteUser".equals(correct)){
            deleteUser(request, response);
        }else if("searchUser".equals(correct)){
            getSearchUser(request, response);
        }
    }

    /**
     * 查询用户
     * @param request
     * @param response
     * @throws IOException
     */
    private void getSearchUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String param = request.getParameter("word");
        List<User> users = userService.getSearchUser(param);
        Result result = new Result();

        result.setCode(0);
        result.setData(users);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 删除用户
     * @param request
     * @param response
     * @throws IOException
     */
    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        Result result = new Result();
        int code = userService.deleteUser(id);

        if (code == 200) {
            result.setCode(0);
        } else  if (code == 500){
            result.setCode(10000);
            result.setMessage("数据库删除异常！");
        }
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 显示用户
     * @param request
     * @param response
     * @throws IOException
     */
    private void allUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> userList = userService.allUser();
        Result result = new Result();
        result.setCode(0);
        result.setData(userList);
        response.getWriter().println(gson.toJson(result));
    }
}